package com.df.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @program: codes
 * @description:
 * @author: df
 * @create: 2023-07-09 13:52:23
 **/
@RestController
public class HelloController {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    //服务发现
    @Autowired
    private DiscoveryClient discoveryClient;

    //负载均衡
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/hello")
    public String hello(){
        //RestTemplate restTemplate = new RestTemplate();
        String s = "";
        // RestTemplate sptring web 提供的HttpClient
        //s = restTemplate.getForObject("http://localhost:8888/hello",String.class);
        // spring cloud consul client 提供了 DiscoveryClient LoadBalancerClient @LoadBalanced
        /*   DiscoveryClient 调用
        List<ServiceInstance> orders = discoveryClient.getInstances("ORDERS");
        ServiceInstance serviceInstance = orders.get(0);
        log.info("host:{},port:{},uri:{}",serviceInstance.getHost(),serviceInstance.getPort(),serviceInstance.getUri());
        s = restTemplate.getForObject(serviceInstance.getUri()+"/hello",String.class);
        */
        //LoadBalancerClient 调用
        //ServiceInstance serviceInstance = loadBalancerClient.choose("ORDERS");
        //s = restTemplate.getForObject(serviceInstance.getUri()+"/hello",String.class);
        s = restTemplate.getForObject("http://ORDERS/hello",String.class);
        return s;
    }
}
